package com.hh.until;

import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailUtil {
    //实现邮件发送的方法
    public static void sendMsg(String recipient, String subject, String content) throws Exception {
        //发件人邮箱和授权码
        String username = "houyang10.17@foxmail.com";
        String pass = "wdrqoaxirhgqbeeh";

        //一、连接邮箱服务器
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.qq.com");  //设置服务器地址

        props.setProperty("mail.smtp.auth", "true");//认证
        //2.产生一个用于邮件发送的Session对象
        Session session = Session.getInstance(props);

        //二、创建邮件对象，设置邮件的参数
        //3.产生一个邮件的消息对象
        MimeMessage message = new MimeMessage(session);

        //4.邮件的发送者
        Address fromAddr = new InternetAddress(username);
        message.setFrom(fromAddr);

        //5.邮件的接收者
        Address toAddr = new InternetAddress(recipient);
        //发送方式  TO 直接发送  CC抄送    BCC密送
        message.setRecipient(MimeMessage.RecipientType.TO, toAddr);

        //6.设置主题
        message.setSubject(subject);
        //7.设置正文
        //设置邮件内容类型
        message.setContent(content, "text/html;charset=utf-8");


        //三、发送邮件
        //8./获取连接对象
        Transport transport = session.getTransport("smtp");
        //9.连接服务器
        transport.connect("smtp.qq.com", username, pass);
        //10.发送邮件
        transport.sendMessage(message, message.getAllRecipients());

        //11.关闭连接
        transport.close();
    }
}
